package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.nio.ByteBuffer;

// Assuming OAD and Get_Result are already defined in Java in their respective files
// and have similar methods as in the TypeScript code.

public class AResultNormal extends AxdrType {
    private ByteBuffer dataCode = null;
    private OAD oad = null;
    private GetResult result = null;

    public AResultNormal() {
    }

    public OAD getOad() {
        return oad;
    }

    public void setDataCode(ByteBuffer dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(OAD oad, GetResult result) {
        this.oad = oad;
        this.result = result;
    }

    public void setOAD(OAD oad) {
        this.oad = oad;
    }

    public void setResult(GetResult result) {
        this.result = result;
    }

    public GetResult getResult() {
        return result;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.oad = new OAD();
        codeLength += this.oad.decode(input);
        this.result = new GetResult();
        codeLength += this.result.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.remaining();
            while (this.dataCode.hasRemaining()) {
                output.write(this.dataCode.get());
            }
        } else {
            if (this.result != null && this.oad != null) {
                codeLength = 0;
                codeLength += this.result.encode(output);
                codeLength += this.oad.encode(output);
            } else {
                throw new Exception("oad or result is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.toByteArray());
    }

    @Override
    public String toString() {
        if (this.oad != null && this.result != null) {
            return "sequence: {" + "oad: " + this.oad + ", result: " + this.result + "}";
        } else {
            return "oad || result is null";
        }
    }
}


